﻿using HomeWork.IDAL;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace HomeWork.DAL
{
    public class BaseDal<T>:IBaseDal<T> where T : class
    {
        MyDbContext db;
        public BaseDal(MyDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="t">实体</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> AddAsync(T t)
        {
            try
            {
                await db.Set<T>().AddAsync(t);
                return await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 单条件查询
        /// </summary>
        /// <param name="expression">查询条件</param>
        /// <returns>符合条件的行数</returns>
        public async Task<T> GetAsync(Expression<Func<T, bool>> expression)
        {
            try
            {
                return await db.Set<T>().Where(expression).FirstOrDefaultAsync();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 获取所有信息
        /// </summary>
        /// <returns>全部数据</returns>
        public IQueryable<T> GetList()
        {
            try
            {
                return db.Set<T>().AsQueryable();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 删除/修改
        /// </summary>
        /// <param name="t">实体</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> UpdateAsync(T t)
        {
            try
            {
                db.Set<T>().Update(t);
                return await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
    }
}
